<template>
	<view class="pageview">
		<firstConnect v-if="isFirst" :device-type="deviceType" :deviceStatus="deviceStatus" @startUse="startUse" @retry="retry"></firstConnect>
		<template v-else>
			<view class="toptip flex align-center justify-between" v-if="!connectedDevice || deviceStatus == 3">
				<text>{{ blueState ? '当前设备未连接，请连接设备' : '需要开启蓝牙，连接设备' }}</text>
				<view class="btn flex align-center" @click="devicesDiscovery" v-if="blueState">
					<u-loading-icon color="#fff" :show="deviceStatus == 0 || deviceStatus == 1"></u-loading-icon>
					<text>去连接</text>
				</view>
			</view>
			<template v-if="deviceStatus == 2">
				<view class="toptip flex align-center justify-between" v-if="contactedStatus != '06'">
					<text>
						{{ contactedStatus == '01' ? '导联未连接，请检测佩戴' : contactedStatus == '02' ? '设备连接异常' : '' }}
					</text>
				</view>
			</template>
			<view class="toolbar flex align-center justify-between">
				<view class="flex align-center">
					<text class="u-margin-right-10">监测时长</text>
					<smh-timer ref="timer" @timing="timing" :auto="false"></smh-timer>
				</view>
				<view>
					<text class="num u-margin-right-10">{{ bpmData || '--' }}</text>
					<text>bpm</text>
				</view>
			</view>
			<view class="charts">
				<view class="charts-box linecharts">
					<qiun-data-charts type="line" :opts="opts1" :chartData="chartData1" canvas2d />
				</view>
				<view class="charts-box linechartsCopy">
					<qiun-data-charts type="line" :opts="opts2" :chartData="chartData" canvas2d />
				</view>
			</view>
		</template>
	</view>
</template>

<script>
import { ab2str, formatNum, formatSecond, chunk } from '@/utils/util';
const ER2Protocol = require('@/utils/ble_devices/er2');
const ERBuilder = {
	// 注意这里的this是实例化后的O2对象，而不是page
	//'0000180F-0000-1000-8000-00805F9B34FB'
	notifyServiceId: ['0000180D-0000-1000-8000-00805F9B34FB', '0000322D-0000-1000-8000-00805F9B34FB'],
	deviceFoundFilter: item => /(ZHS)/.test(item.name),
	connectionStateChange: function (res) {
		console.log('ER连接状态改变', res);
		this.connectionState = res.connected;
	},
	characteristicValueChange: function (res) {
		if (res.value) {
			// 开始解析数据
			if (res.value !== this.oldCallbackData) {
				//可能会有重复的包
				this.oldCallbackData = res.value;
				// 而且微信返回的value是ArrayBuffer，所以同样要先转换成str
				if (res.serviceId == '0000322D-0000-1000-8000-00805F9B34FB') {
					this.parseData(ab2str(res.value));
				} else if (res.serviceId == '0000180D-0000-1000-8000-00805F9B34FB') {
					//心率
					this.parseBPMData(ab2str(res.value));
				}
			}
		}
	}
};

const ER = new ER2Protocol(ERBuilder);
let foundTimer = null,
	saveTimer = null;
var LineCIds = null;
import firstConnect from './components/firstConnect';
import O2Chart from './components/O2Chart';
import stompMixin from '@/common/stompMixin.js';
import { mapState } from 'vuex';
export default {
	mixins: [stompMixin],
	data() {
		return {
			isConnected: false, // 是否连接设备
			devicesDiscovered: [], // 设备列表
			connectedDevice: null, // 当前连接设备
			deviceType: 'ER',
			deviceTypeId: '',
			isFirst: true,
			deviceStatus: -1,
			deviceData: [],
			blueState: false, //蓝牙状态
			chartData1: {
				categories: [],
				series: [
					{
						name: '122',
						data: []
					}
				]
			},
			chartData: {
				categories: [],
				series: [
					{
						name: '122',
						data: []
					}
				]
			},
			opts1: {
				rotate: false,
				rotateLock: false,
				color: ['#63b3f8'],
				padding: [0, 0, 0, 0],
				legend: {
					show: false
				},
				dataLabel: false,
				dataPointShape: false,
				animation: false,
				update: true, // 关键：是否开启连续更新数据的方法,开启之后就不会抖动了
				duration: 0,
				xAxis: {
					disabled: true, //不显示x轴
					disableGrid: false,
					boundaryGap: 'justify',
					type: 'grid',
					gridColor: '#DBB7BB',
					gridType: 'dash',
					dashLength: 0.5,
					gridEval: 10,
					data: [
						{
							min: 1,
							max: 350
						}
					],
					splitNumber: 1
				},
				yAxis: {
					disabled: true, //不显示y轴
					// disableGrid: false,
					gridType: 'dash',
					gridColor: '#DBB7BB',
					dashLength: 0.5,
					gridEval: 1,
					splitNumber: 30,
					data: [
						{
							min: -1.5,
							max: 1.5
						}
					]
				},
				extra: {
					tooltip: {
						showBox: false,
						splitLine: false
					},
					line: {
						activeType: 'none'
					}
				}
			},
			opts2: {
				rotate: false,
				rotateLock: false,
				color: ['#63b3f8'],
				padding: [0, 0, 0, 0],
				legend: {
					show: false
				},
				dataLabel: false,
				dataPointShape: false,
				animation: false,
				update: true, // 关键：是否开启连续更新数据的方法,开启之后就不会抖动了
				duration: 0,
				xAxis: {
					disableGrid: false,
					boundaryGap: 'justify',
					disabled: true,
					type: 'grid',
					gridColor: '#aa0000',
					gridType: 'solid',
					gridEval: 50,
					data: [
						{
							min: 1,
							max: 350
						}
					],
					splitNumber: 1
				},
				yAxis: {
					disabled: true,
					gridType: 'solid',
					gridColor: '#aa0000',
					gridEval: 5,
					splitNumber: 6,
					data: [
						{
							min: -1.5,
							max: 1.5
						}
					]
				},
				extra: {
					tooltip: {
						showBox: false,
						splitLine: false
					},
					line: {
						activeType: 'none'
					}
				}
			},
			ecglist: [],
			oldecglist: [],
			bpmData: null,
			contactedStatus: '01' //导联未连接
		};
	},
	computed: {
		...mapState(['userInfo', 'curAccount'])
	},
	components: {
		firstConnect
	},
	onLoad(optioin) {
		this.deviceType = optioin.deviceType;
		if (optioin.deviceTypeId) {
			this.deviceTypeId = optioin.deviceTypeId;
			this.isFirst = true;
		} else {
			this.deviceMac = optioin.deviceMac;
			this.isFirst = false;
		}
		const appInstance = getApp();
		appInstance.watch(this, ER, {
			//蓝牙配置状态
			adapterState: function (newVal) {
				if (newVal && !this.blueState) {
					this.blueState = true; //设置蓝牙初始化成功了
					this.deviceStatus = -1;
					if (this.isFirst) {
						this.devicesDiscovery();
					}
				}
			},
			foundDevices: function (newVal) {
				if (newVal && newVal.length > 0) {
					this.devicesDiscovered = newVal;
					if (this.devicesDiscovered.length > 0 && !this.isConnected) {
						let index = -1;
						if (this.deviceMac) {
							index = this.devicesDiscovered.findIndex(item => item.deviceId == this.deviceMac);
						} else {
							index = this.devicesDiscovered.findIndex(item => /(ZHS)/.test(item.name));
						}
						if (index > -1) {
							this.deviceStatus = 1;
							this.connectToDevice(index);
							clearTimeout(foundTimer);
							foundTimer = null;
						}
					}
				}
			},
			connectedDevice: function (newVal) {
				this.isConnected = !!newVal;
				this.connectedDevice = newVal;
				this.deviceStatus = 2;
				if (this.isFirst) {
					this.addDevice();
				} else {
					this.getRealTimeEcg();
				}
			},
			bpm: function (newVal) {
				this.bpmData = newVal;
			},
			connectionState: function (newVal) {
				this.deviceStatus = newVal ? 2 : 3;
				//表示链接断开了
				if (this.deviceStatus == 3) {
					ER.foundDevices = [];
				}
			},
			contactedStatus: function (newVal) {
				this.contactedStatus = newVal;
			}
		});
		ER.init();
	},
	onUnload() {
		// 不在当前页面的时候断开连接
		this.disconnectToDevice();
		// 关闭实时指令timer
		this.stopRealTimeEcg();
		//如果还在查找设备，先停止查找
		if (foundTimer || this.deviceStatus == 0) {
			this.clearfoundTimer();
		}
	},
	methods: {
		// 搜索周围设备
		devicesDiscovery() {
			this.deviceStatus = 0;
			ER.startDevicesDiscovery();
			//5s没有找到设备，就提示没有发现设备
			foundTimer = setTimeout(() => {
				this.clearfoundTimer();
			}, 5000);
		},
		// 连接指定设备
		connectToDevice(index) {
			ER.stopDevicesDiscovery();
			const targetDevice = this.devicesDiscovered[index];
			ER.connectToDevice(targetDevice).then(() => {});
		},
		// 断开当前连接设备
		disconnectToDevice() {
			ER.disconnectToDevice();
		},
		startUse() {
			this.isFirst = false;
			this.getRealTimeEcg();
		},
		getRealTimeEcg() {
			this.$nextTick(() => {
				this.start();
			});
			//x轴数据
			let categories = [],
				data = [];
			for (var i = 0; i < 351; i++) {
				categories.push(i);
				data.push(0);
			}
			this.chartData1 = JSON.parse(
				JSON.stringify({
					categories,
					series: [
						{
							name: '12',
							data: []
						}
					]
				})
			);
			this.chartData = JSON.parse(
				JSON.stringify({
					categories,
					series: [
						{
							name: '12',
							data: data
						}
					]
				})
			);
			this.oldecglist = [...data];
			this.ecglist = [];
			//定时更新数据心电
			LineCIds = setInterval(() => {
				//y轴数据
				let nowWave = ER.drawEcg();
				if (nowWave.length == 0) {
					for (var i = 0; i < 50; i++) {
						nowWave.push(0);
					}
				}
				let ecglist = [...this.ecglist, ...nowWave];
				let nowWaveList = [];
				if (ecglist.length <= 350) {
					this.ecglist = [...ecglist];
					nowWaveList = [...ecglist, ...this.oldecglist.slice(ecglist.length)];
					for (let i = 0; i < 5; i++) {
						nowWaveList[(ecglist.length + i + 1) % 350] = null;
					}
				} else {
					const len1 = ecglist.length % 350;
					let dlist = ecglist.splice(350);
					this.ecglist = [...dlist];
					this.oldecglist = [...ecglist];
					ecglist.splice(0, len1, ...dlist);
					nowWaveList = [...ecglist];
					for (let i = 0; i < 5; i++) {
						nowWaveList[(len1 + i + 1) % 350] = null;
					}
				}

				// console.log('nowWaveList', nowWaveList);
				this.chartData = JSON.parse(
					JSON.stringify({
						categories,
						series: [
							{
								name: '12',
								data: nowWaveList
							}
						]
					})
				);
			}, 50);
			saveTimer = setInterval(() => {
				this.deviceData = ER.saveEcgList();
				if (this.deviceData.length > 0) {
					this.save();
				}
			}, 3000);
		},
		// 停止实时监听
		stopRealTimeEcg() {
			//关闭计时
			this.clear();
			//清除图表更新
			if (LineCIds) {
				clearInterval(LineCIds);
				LineCIds = null;
			}
			//清除定时保存
			if (saveTimer) {
				clearInterval(saveTimer);
				saveTimer = null;
			}
			if (ER.allWaveData.length > 0) {
				this.deviceData = ER.allWaveData;
				this.save();
			}
		},
		retry() {
			this.deviceStatus = 0;
			this.devicesDiscovery();
		},
		addDevice() {
			this.$postAction(this.$deviceapi.addDevice, {
				bindState: 1,
				deviceTypeId: this.deviceTypeId,
				userId: this.userInfo.userId,
				devName: this.connectedDevice.name,
				mac: this.connectedDevice.deviceId
			});
		},
		save() {
			this.send(
				JSON.stringify({
					detailId: this.curAccount.detailId,
					type: this.deviceType,
					data: this.deviceData
				})
			);
		},
		timing(second) {
			//实时返回计时时间
			// console.log(second);
		},
		reset() {
			//重置计时器
			this.$refs.timer.reset();
		},
		start() {
			//手动开启计时器
			this.$refs.timer.start();
		},
		clear() {
			//停止计时器
			this.$refs.timer.clear();
		},
		clearfoundTimer() {
			ER.stopDevicesDiscovery();
			clearTimeout(foundTimer);
			foundTimer = null;
			this.deviceStatus = 3;
		}
	}
};
</script>

<style scoped lang="scss">
.pageview {
	background: #f2f2f2;
	height: 100vh;
}

.toptip {
	background: #fff;
	padding: 30upx 20upx;
	position: absolute;
	top: 0;
	left: 0;
	right: 0;

	.btn {
		background: $u-primary;
		padding: 0 20upx;
		color: #fff;
		border-radius: 50upx;
		line-height: 60upx;
	}
}

.toolbar {
	background: #fff;
	padding: 20upx;

	.num {
		font-size: 60upx;
		font-weight: 600;
	}
}

.charts {
	width: 100%;
	height: 600upx;
	background: #fff;
	margin-top: 30upx;
	padding: 20upx;
	box-sizing: border-box;
	position: relative;
}

.charts-box {
	width: 100%;
	height: 560upx;

	// border: 1px solid #f00;
	&.linechartsCopy {
		width: auto;
		position: absolute;
		left: 20upx;
		right: 20upx;
		top: 20upx;
	}
}
</style>
